<script setup lang="ts">
import { reactive, computed, shallowRef, ref } from 'vue';
import formPricker from '@/components/formPricker.vue';
import formDatePricker from '@/components/formDatePricker.vue';
import formAreaPricker from '@/components/formAreaPricker.vue';
import { useLargenScreen } from '@/composables/useLargenScreen';
import { useGetAreaJson } from '@/composables/getAreaJson';
import { useBankList } from './hooks/getHfBankList';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import headerNavBar from '@/components/headerNavBar.vue';
import { useToastLoading } from '@/composables/useToastLoading';
import { myAccountDetail, UserApplyBankUpd, CompanyApplyBankUpd } from '@/common/api/bankCard';

const router = useRouter();

// 监听浏览器窗口变化
const [largenScreen] = useLargenScreen();

// 定义引用
const cardCertEndDateRef = shallowRef();

// 获取省市区json数据
const [areaPrickerOptions] = useGetAreaJson();
// 银行列表
const { bankList } = useBankList();

const form = reactive({
  register_type: '1', // 进件类型 1：个人进件 2：企业进件
  // 结算卡信息
  card_info: {
    card_type: '1', // 卡类型 0：对公，1：对私，2：对私非法人
    card_name: '', // 卡户名 公司名称
    card_no: '', // 卡号 银行卡号；不支持贷记卡绑定
    prov_id: '', // 银行所在省 参见 地区编码
    area_id: '', // 参见 地区编码
    bank_code: '', // 银行号
    bank_type: '', // 银行类型
    branch_name: '', // 支行名称
    cert_no: '', // 持卡人证件号码 对私必填
    cert_validity_type: '', // 持卡人证件有效期类型 对私必填 1:长期有效 0:非长期有效
    cert_begin_date: '', // 持卡人证件有效期开始日期 对私必填
    cert_end_date: '', // 持卡人证件有效期截止日期 当cert_validity_type=0时必须填写，当cert_validity_type=1可不填
  },
});

// 持卡人信息
const cardName = computed(() => (form.card_info.card_type === '0' ? '公司名称' : '持卡人姓名'));

// 校验正则
const certNoPattern =
  /^(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|71|8[1-2])\d{4}(19\d{2}|20[0-2]\d)(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}([0-9Xx])$/; // 身份证正则校验

const detailLoading = ref(false);
const loading = ref(false);

const onSubmit = () => {
  if (form.register_type === '1') {
    handleUserApplyBankUpd();
  } else if (form.register_type === '2') {
    handleCompanyApplyBankUpd();
  } else {
    showToast('进件类型错误');
  }
};

// 个人进件绑卡修改
const handleUserApplyBankUpd = async () => {
  loading.value = true;
  try {
    await UserApplyBankUpd({
      ...form.card_info,
      prov_id: form.card_info.prov_id.padEnd(6, '0'),
      area_id: form.card_info.area_id.padEnd(6, '0'),
    });
    router.back();
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};

// 企业进件绑卡修改
const handleCompanyApplyBankUpd = async () => {
  loading.value = true;
  try {
    await CompanyApplyBankUpd({
      ...form.card_info,
      prov_id: form.card_info.prov_id.padEnd(6, '0'),
      area_id: form.card_info.area_id.padEnd(6, '0'),
    });
    router.back();
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};

// 获取用户进件信息
const getHfUserApplyInfo = async () => {
  detailLoading.value = true;
  try {
    const res = await myAccountDetail({});
    if (!res.result.data.param) {
      return;
    }
    window.document.title = '用户基本信息开户详情';

    const param = JSON.parse(res.result.data?.param || '{}');
    const preparam = JSON.parse(res.result.data?.preparam || '{}');

    // 持卡人信息
    if (param.card_info) {
      param.card_info = JSON.parse(param.card_info);
      Object.assign(form.card_info, {
        ...param.card_info,
        name: param.card_info.name || param.card_info.card_name,
        prov_id: param.card_info.prov_id.slice(0, 2),
        area_id: param.card_info.area_id.slice(0, 4),
      });
    }
    // 个人开户信息
    if (preparam.mobile_no) {
      form.register_type = '1';
    }
    // 企业开户信息
    if (preparam.reg_name) {
      form.register_type = '2';
    }
  } catch {
    /** empty */
  } finally {
    detailLoading.value = false;
  }
};
getHfUserApplyInfo();
useToastLoading(detailLoading);
</script>
<template>
  <div class="userInfoOpenAccountEdit" :class="{ boxShadow: largenScreen }">
    <headerNavBar />
    <van-form @submit="onSubmit" label-align="top" scroll-to-error required="auto">
      <div class="title">持卡人信息</div>
      <form-pricker
        v-if="form.register_type === '2'"
        v-model="form.card_info.card_type"
        ref="cardTypeRef"
        label="结算类型"
        name="card_info_card_type"
        :columns="[
          { text: '对公', value: '0' },
          { text: '对私', value: '1' },
        ]"
      />
      <van-field
        label-class="u_label"
        v-model.trim="form.card_info.card_name"
        name="card_name"
        :label="cardName"
        :placeholder="`请输入${cardName}`"
        :rules="[{ required: true, message: `请填写${cardName}` }]"
      />
      <template v-if="form.card_info.card_type == '1'">
        <form-pricker v-model="form.card_info.bank_type" label="银行类型" name="card_bank_type" :columns="bankList" />
      </template>

      <van-field
        label-class="u_label"
        v-model="form.card_info.card_no"
        name="card_no"
        type="number"
        label="银行卡号"
        clearable
        clear-trigger="always"
        placeholder="请输入银行卡号"
        :rules="[
          { required: true, message: '请填写银行卡号' },
          { pattern: /\d/, message: '请正确输入银行卡号' },
        ]"
      />
      <formAreaPricker
        :model-value="[form.card_info.prov_id, form.card_info.area_id]"
        label="银行所在省/市"
        name="area"
        :columns="areaPrickerOptions"
        @on-confirm="
          (value) => {
            form.card_info.prov_id = value[0].value;
            form.card_info.area_id = value[1].value;
          }
        "
      />
      <template v-if="form.card_info.card_type == '0'">
        <form-pricker
          v-model="form.card_info.bank_code"
          label="银行号"
          name="card_bank_code"
          :columns="[
            { text: '中国银行	', value: '01040000' },
            { text: '中国农业银行', value: '01030000' },
            { text: '中国工商银行', value: '01020000' },
            { text: '中国建设银行', value: '01050000' },
            { text: '交通银行', value: '03010000' },
            { text: '中国邮政储蓄银行', value: '04030000' },
            { text: '华夏银行', value: '03040000' },
            { text: '招商银行', value: '03080000' },
            { text: '上海浦东发展银行', value: '03100000' },
            { text: '浙商银行', value: '03160000' },
            { text: '广发银行', value: '03060000' },
            { text: '天津银行', value: '03130012' },
            { text: '济宁银行', value: '31346100' },
            { text: '中国民生银行', value: '03050000' },
          ]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.card_info.branch_name"
          name="branch_name"
          label="支行名称"
          placeholder="请输入支行名称"
          :rules="[{ required: true, message: '请填写支行名称' }]"
        />
      </template>
      <template v-else-if="form.card_info.card_type == '1'">
        <van-field
          label-class="u_label"
          v-model.trim="form.card_info.cert_no"
          name="cert_no"
          label="持卡人证件号码"
          placeholder="请输入持卡人证件号码"
          clearable
          clear-trigger="always"
          :rules="[
            { required: true, message: '请填写持卡人证件号码' },
            { pattern: certNoPattern, message: '请正确输入持卡人证件号码' },
          ]"
        />
        <form-pricker
          v-model="form.card_info.cert_validity_type"
          label="持卡人证件有效期类型"
          name="card_cert_validity_type"
          :columns="[
            { text: '非长期有效', value: '0' },
            { text: '长期有效', value: '1' },
          ]"
        />
        <formDatePricker
          v-model="form.card_info.cert_begin_date"
          label="持卡人证件有效期开始日期"
          name="legal_cert_begin_date"
          @onConfirm="
            (value) => {
              cardCertEndDateRef?.setValue(value);
            }
          "
        />
        <template v-if="form.card_info.cert_validity_type == '0'">
          <formDatePricker
            ref="cardCertEndDateRef"
            v-model="form.card_info.cert_end_date"
            label="持卡人证件有效期截止日期"
            name="card_cert_end_date"
          />
        </template>
      </template>
      <div class="submitBox">
        <van-button
          round
          block
          type="primary"
          :disabled="detailLoading"
          class="mr-10"
          color="#EC2D69"
          native-type="submit"
          :loading="loading"
        >
          提交
        </van-button>
      </div>
      <div class="tip">修改完隔天生效</div>

      <!-- 底部安全区 -->
      <div class="van-safe-area-bottom"></div>
    </van-form>
  </div>
</template>
<style lang="less" scoped>
.userInfoOpenAccountEdit {
  max-width: 400px;
  margin: 0 auto;
  .title {
    font-size: 12px;
    color: #8a8a8a;
    margin: 15px 15px 7.5px;
  }
  .submitBox {
    margin: 16px;
    display: flex;
  }
  .tip {
    margin-top: 10px;
    text-align: center;
    color: red;
  }
}
.userInfoOpenAccountEdit.boxShadow {
  margin: 3vh auto;
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  min-height: 80vh;
}
</style>
../../composables/getAreaJson
